package com.iss.card.view.store;

import java.util.ArrayList;
import java.util.List;

import android.R.integer;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Application;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import com.iss.card.CardController;
import com.iss.card.CardController.EventType;
import com.iss.card.R.array;
import com.iss.card.R;
import com.iss.card.common.ApplicationManager;
import com.iss.card.common.CommonValue;
import com.iss.card.common.FunctionUtil;
import com.iss.card.common.IBackKeyListener;
import com.iss.card.common.Tools;
import com.iss.card.view.ContainerActivity;
import com.iss.card.view.model.ResponseBean;
import com.iss.card.view.mycard.CardBagModel;
import com.iss.card.view.overrideview.IOnClickEventListener;
import com.iss.card.view.overrideview.SlideViewGroup;
import com.iss.card.webservice.BaseModel;
import com.iss.card.webservice.WebServiceAsyncService;
import com.iss.card.webservice.WebServiceAsyncServiceHelper;
import com.iss.card.webservice.WebServiceUtils;
import com.iss.card.webservice.WebServiceAsyncService.Operation;
import com.iss.card.webservice.WebServiceAsyncService.PostExecute;
import com.iss.card.webservice.WebServiceManager.WebServiceRegistrationParameter;
import com.iss.card.webservice.WebServiceManager.WebServiceUrlPortManager;
import com.zxing.activity.CaptureActivity;

/**
 * �̼ҵ���
 */
public class StoreFragment extends Fragment implements IBackKeyListener{
	private static final String TAG = StoreFragment.class.getSimpleName();
	private static final int BARCODE_SCANNER_INTENT = 1000;
	private Context mContext;

	private StoreView mStoreView;

	private SlideViewGroup mGroup;

	private TextView mCityName;
	private TextView mTypeName;

	private StoreFilterFragment mStoreFilterFragment;

	private ArrayList<CardBagModel> cardListFromBarCode;
	private Handler myHandler;
	private String[] barCodeInfo;
	
	@Override
	public void onAttach(Activity activity) {
		super.onAttach(activity);
		mContext = activity;
		Log.d(TAG, "onAttach:");
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		Log.d(TAG, "onCreateView:");
		cardListFromBarCode = new ArrayList<CardBagModel>();
		myHandler = new MyHandler();
		View view = inflater.inflate(R.layout.frame_store_list_view1,
				null);
		mGroup = (SlideViewGroup) view.findViewById(R.id.sv_store_list_view);
		mStoreFilterFragment = (StoreFilterFragment) getFragmentManager()
				.findFragmentById(R.id.slide_store_filter_view);
		mStoreFilterFragment
				.setOnClickEventListener(new IOnClickEventListener() {

					@Override
					public void onClickItemInList() {
						if (mStoreView != null) {
							mStoreView.onHiddenChanged(false);
						}
						updateWindowVisibleRect();
					}
				});
 
		Button storeFilter = (Button) view.findViewById(R.id.store_filter);
		storeFilter.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				// Jump to store filter view.
				mStoreView.setClickTarget(StoreView.CLICK_TARGET_CITY);
				updateWindowVisibleRect();
			}
		});

		Button qrDecoder = (Button) view.findViewById(R.id.qr_decoder);
		qrDecoder.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				Intent i = new Intent(mContext, CaptureActivity.class);
				startActivityForResult(i, BARCODE_SCANNER_INTENT);
			}
		});

		mCityName = (TextView) view.findViewById(R.id.store_city_name);
		((Button) view.findViewById(R.id.bt_background_store_city_selected))
				.setOnClickListener(new View.OnClickListener() {
					@Override
					public void onClick(View v) {
						onClickCitySelected();
						// Toast.makeText(mContext, "Click city name",
						// Toast.LENGTH_SHORT).show();
					}
				});

		mTypeName = (TextView) view.findViewById(R.id.store_type_name);
		refreshHeadSectionContent();

		mStoreView = new StoreView(mContext, view);
		return view;
	}

	@Override
	public void onPause() {
		super.onPause();
		Log.d(TAG, "onPause:");
	}

	@Override
	public void onStart() {
		super.onStart();
		Log.d(TAG, "onStart:");
	}

	@Override
	public void onResume() {
		super.onResume();
		Log.d(TAG, "onResume:");
	}

	/*
	 * (non-Javadoc) it will be invoked while this fragment's status is changed.
	 * hidden true means this fragment is hidden and false means it is visible.
	 * 
	 * @see android.support.v4.app.Fragment#onHiddenChanged(boolean)
	 */
	@Override
	public void onHiddenChanged(boolean hidden) {
		super.onHiddenChanged(hidden);
		Log.d(TAG, "onHiddenChanged: " + hidden);
		if (!hidden && mStoreView != null) { // this fragment is visible.
			mStoreView.onHiddenChanged(hidden);
		}
	}

	@Override
	public void onDestroyView() {
		super.onDestroyView();
		Log.d(TAG, "onDestroyView");
	}

	@Override
	public void onDestroy() {
		super.onDestroy();
		Log.d(TAG, "onDestroy");
	}

	private void onClickCitySelected() {
		mStoreView.setClickTarget(StoreView.CLICK_TARGET_TYPE);
		CardController.getInstance(mContext).sendEvent(
				EventType.ACCOUNT_CITYLIST);
	}

	/**
	 * update visible rect in window.
	 */
	private void updateWindowVisibleRect() {
		if (!mGroup.toggle()) {
			// side menu view hide.
			refreshHeadSectionContent();
		} else {
			mStoreFilterFragment.onScrollToFront();
		}

		// redraw current view in window.
		mStoreView.invalidate();
	}

	private void refreshHeadSectionContent() {
		mTypeName.setText(FunctionUtil.getSelectedStoreType().getTypeName());
		mCityName.setText(FunctionUtil.getSelectedCityInfo().getCityName());
	}

	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		if(requestCode == BARCODE_SCANNER_INTENT){
			if(resultCode == Activity.RESULT_OK){
				String result = data.getExtras().getString("result");
				
				if(!barCodeFormatCheck(result)){
					Tools.showToast(mContext, R.string.barcode_scanner_error);
					return;
				}
				barCodeInfo = result.split(ApplicationManager.BARCODE_RESULT_SPLITOR);
				if(!FunctionUtil.isUserLogIn()){
					goToStoreDetil(barCodeInfo[0]);
				}else{
					myHandler.sendEmptyMessage(ApplicationManager.GET_CARD_LIST_BY_STORE_ID_START);
				}
				
			}
		}
	}
	private boolean barCodeFormatCheck(String barCodeInfo){
		
		if(barCodeInfo.contains(ApplicationManager.BARCODE_RESULT_SPLITOR)
				&& barCodeInfo != null){
			String[] mInfoList = barCodeInfo.split(ApplicationManager.BARCODE_RESULT_SPLITOR);
			if(TextUtils.isDigitsOnly(mInfoList[0])){
				return true;
			}
			return false;
		}
		return false;
	}
	private void goToStoreDetil(String storeId){
		Intent intent = new Intent(mContext, ContainerActivity.class);
		intent.putExtra(
				ApplicationManager.KEY_PUT_EXTRA_SELECTED_STORE_ID,
				storeId);
		intent.putExtra(
				ApplicationManager.KEY_PUT_EXTRA_DEFAULT_PRODUCT_ID,
				0);
		intent.putExtra(ApplicationManager.INTENT_KEY,
				ApplicationManager.INTENT_FRAGMENT_STORE_DETAIL);
		startActivity(intent);
		
	}
	
/*	private boolean hasCard(String storeId){
		doGetCardListByStoreId(FunctionUtil.getCurrentLoginUserMobile(), storeId);
		return false;
	}*/
	
	private void doGetCardListByStoreId(String id){
		String[] obj = {FunctionUtil.getCurrentLoginUserMobile(), id};
		WebServiceAsyncService webService = new WebServiceAsyncService();
		webService.setParameterToAsyncService(mContext,
				webService.getNextToken(), 
				Operation.OP_SERVICE_ARG_GET_CARD_LIST_BY_STORE_ID,
				WebServiceRegistrationParameter.PARAMETERS_GET_CARD_LIST_BY_STORE_ID,
				obj,
				WebServiceUrlPortManager.ACTION_URL_PORT_GET_CARD_BY_STORE_ID, 
				this,
				WebServiceAsyncServiceHelper.TYPE_HTTP_GET_INSTREAM);
		webService.setPostExecute(new PostExecute() {
			@Override
			public void onAsyncServiceComplete(int token, Object result,
					int index) {
				cardListFromBarCode.clear();
				ResponseBean response = WebServiceUtils
						.getObjectResultToBaseInfo(result, CardBagModel.class);
				if(response.getStatus() != ApplicationManager.RESPONSE_OK){
					for(BaseModel info : response.getReturnList()){
						cardListFromBarCode.add((CardBagModel)info);
					}
					myHandler.sendEmptyMessage(ApplicationManager.GET_CARD_LIST_BY_STORE_ID_END);
				}else {
					Tools.showToast(mContext, response.getMessage());
					return;
				}
				
			}
		});
	}

	@Override
	public void cancelUpdate(Object... params) {
		// TODO Auto-generated method stub
		
	}
	
	public void isGoToCard(){
		if(!FunctionUtil.isUserLogIn()){
			goToStoreDetil(barCodeInfo[0]);
			return;
		}
		if(cardListFromBarCode == null || cardListFromBarCode.size() == 0){
			goToStoreDetil(barCodeInfo[0]);
			return;
		}
		AlertDialog dlg = new AlertDialog.Builder(mContext)
		.setTitle(mContext.getString(R.string.barcode_alert_title))
		.setMessage(mContext.getString(R.string.barcode_alert_message))
		.setPositiveButton(mContext.getString(R.string.barcode_goto_card), 
				new DialogInterface.OnClickListener() {
					
					@Override
					public void onClick(DialogInterface dialog, int which) {
						ApplicationManager.IS_CARD_LIST_BY_STORE_ID = true;
						FunctionUtil
						.setCurrentPageIndex(CommonValue.EnumPageIndex.EPageCardList);
						
						CardController.getInstance(mContext)
						.sendEvent(EventType.CARDBAG_CONTENT,cardListFromBarCode);
						ApplicationManager.STORE_ID_FOR_CARD_LIST = barCodeInfo[0];
						
					}
				})
		 .setNegativeButton(mContext.getString(R.string.barcode_goto_store), 
				 new DialogInterface.OnClickListener() {
					
					@Override
					public void onClick(DialogInterface dialog, int which) {
						goToStoreDetil(barCodeInfo[0]);
					}
				})
		 .create();
		dlg.show();
	}
	class MyHandler extends Handler{

		public MyHandler() {
        }

        public MyHandler(Looper L) {
            super(L);
        }
		@Override
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case ApplicationManager.GET_CARD_LIST_BY_STORE_ID_START:
				doGetCardListByStoreId(barCodeInfo[0]);
				break;
			case ApplicationManager.GET_CARD_LIST_BY_STORE_ID_END:
				isGoToCard();
				break;
			default:
				break;
			}
		}
		
	}
}
